﻿// Copyright @ shch8.com All Rights Reserved At 2008-3-6
//开发：商创技术（www.shch8.com）望月狼
/*
·字符处理
 可直接按参数直接调用

 例：strUtil.isEmail("wzh3847@sina.com")//验证邮件格式是否正确，返回boolean值

 */
package com._public._utils{
	import flash.text.TextField;
	import flash.text.TextFormat;

	public class strUtil {
        /**
		  * 字符省略，截取所定字符长度省略显示
		  * @param	str			原字符串
		  * @param	str_limt	限制长度
		  * @param	moreStr		省略时替加字符
		  * @return
		  */
		public static function strLime(str:String,str_limt:int,moreStr:String=".."):String {
			if (str.length>str_limt) {//字符过长截取
				return str.substring(0,str_limt) + moreStr;
			}
			return str;
		}
		/**
		 * 字符转日期:2011-01-19 00:00:00
		 * @param	char
		 * @return Boolean
		 */
		public static function strToDate(value:String):Date {
			if (value == null) return null;
			var dateAry:Array = value.slice(0,value.indexOf(" ")).split("-")
			var hourAry:Array = value.slice(value.indexOf(" ")).split(":")
			var date:Date = new Date(dateAry[0], dateAry[1], dateAry[2], hourAry[0], hourAry[1])
			if (hourAry.length == 3) date.seconds = hourAry[2];
			return date
		}
		/**
		 * 日期字符串:2011-01-19 00:00:00
		 * @param	date
		 * @param	useHours 是否使用小时时间
		 * @return
		 */
		public static function dateToString(date:Date,useHours:Boolean=true):String {
			var str:String= date.fullYear + "-" + getNum(date.month) + "-" + getNum(date.date)
			if(useHours)str+=" "+getNum(date.hours)+":"+getNum(date.minutes)+":"+getNum(date.seconds)
			return str
			function getNum(value:int):String {
				return value < 10?("0" + value):String(value)
				}
		}
		/**
		 * 获取当前时间的字符串，用于唯一编号ID中
		 * @return
		 */
		public static function getNowStr():String{
			var date:Date=new Date
			var getStr:String=String(date.fullYear)+date.month+date.date+date.hours+date.minutes+date.seconds;
			getStr += uint(Math.random() * 100)
			return getStr;
		}
		/**
		 * XML格式效正字符,用于XML表中因该禁用的字符: " ' < > &
		 * @param	char
		 * @return Boolean  true:合法 false不合法
		 */
		public static function checkSen(char:String):Boolean {
			var pattern:RegExp = /.\"|.\'|.<|.>|.&/;
			return ! pattern.test(char);
		}
		/**
		 * createText中使用的文件样式
		 */
		public static var textFormat:TextFormat;
		/**
		 * 创建文本块
		 * @param	removeAll	是否禁用所有属性
		 * @param	wid
		 * @return
		 */
		public static function createText(removeAll:Boolean=false,wid:int=0):TextField 
		{
			var txt:TextField = new TextField
			txt.tabEnabled = false;
			if (textFormat != null) txt.defaultTextFormat = textFormat;
			txt.autoSize = "left";
			if(wid!=0){
				txt.wordWrap=true
				txt.width = wid;
				}
			txt.selectable = false;
			txt.alwaysShowSelection = false;
			txt.mouseWheelEnabled = false;
			if (removeAll) {
				txt.mouseEnabled = false;
				}
			return txt
		}
		/**
		 * 字符型转布尔型
		 * @param	char
		 * @return
		 */
		public static function strToBoolean(char:String):Boolean {
			if (char == "true") {
				return true;
				}
			if (char == "true") {
				return false;
				}
			return false;
		}
		/**
		 * 使用转意字符,为了在XML文档中使用,转成XMIFF替换符,请过滤(&)符再替换:" ' < >
		 * @param	string  需处理的字符
		 * @return  String
		 */
		public static function replyXmlStr(string:String = ""):String {
			//tag1是双引号,tag2是单引号,tag3是&号
			replay("&","&amp;");
			replay("<","&lt;");
			replay(">","&gt;");
			replay("\"","&quot;");
			replay("\'","&apos;");
			function replay(restr:String,endstr:String):void {
				var end:*;
				var font:String;
				var usestr:String="";
				var pattern:RegExp=new RegExp("."+restr);
				while (pattern.test(string)) {//先过替换掉&符号
					end=string.indexOf(restr);
					font =string.substring(0, end);
					end = string.substring(end+1);
					usestr += font+endstr;
					string=end;
				}
				string=usestr+end;
			}
			return string;
		}
		/**
		 * 忽略大小字母比较字符是否相等;
		 * @param	char1	比较字符一
		 * @param	char2	比较字符一
		 * @return
		 */
		public static function equalsIgnoreCase(char1:String,char2:String):Boolean {
			return char1.toLowerCase() == char2.toLowerCase();
		}
		/**
		 * 判断是否为Email地址
		 * @param	char  判断字符
		 * @return
		 */
		public static function isEmail(char:String):Boolean {
			if (char == null||char=="") {
				return false;
			}
			char = trim(char);
			var pattern:RegExp = /(\w|[_.\-])+@((\w|-)+\.)+\w{2,4}+/;
			var result:Object = pattern.exec(char);
			if (result == null) {
				return false;
			}
			return true;
		}
		/**
		 * 判断是否是数值字符串;
		 * @param	char 判断字符
		 * @return
		 */
		public static function isNumber(char:String):Boolean {
			if (char == null) {
				return false;
			}
			return ! isNaN(Number(char));
		}
		/**
		 * 是否为Double型数据;
		 * @param	char 判断字符
		 * @return
		 */
		public static function isDouble(char:String):Boolean {
			char = trim(char);
			var pattern:RegExp = /^[-\+]?\d+(\.\d+)?$/;
			var result:Object = pattern.exec(char);
			if (result == null) {
				return false;
			}
			return true;
		}
		/**
		 * 是否为整型
		 * @param	char
		 * @return
		 */
		public static function isInteger(char:String):Boolean {
			if (char == null) {
				return false;
			}
			char = trim(char);
			var pattern:RegExp = /^[-\+]?\d+$/;
			var result:Object = pattern.exec(char);
			if (result == null) {
				return false;
			}
			return true;
		}
		/**
		 * 是否为纯英文字符
		 * @param	char
		 * @return
		 */
		public static function isEnglish(char:String):Boolean {
			if (char == null) {
				return false;
			}
			char = trim(char);
			var pattern:RegExp = /^[A-Za-z]+$/;
			var result:Object = pattern.exec(char);
			if (result == null) {
				return false;
			}
			return true;
		}
		/**
		 * 是否为中文字符
		 * @param	char
		 * @return
		 */
		public static function isChinese(char:String):Boolean {
			if (char == null) {
				return false;
			}
			char = trim(char);
			var pattern:RegExp = /^[\u0391-\uFFE5]+$/; ;
			var result:Object = pattern.exec(char);
			if (result == null) {
				return false;
			}
			return true;
		}
		/**
		 * 是否为双字节符
		 * @param	char
		 * @return
		 */
		public static function isDoubleChar(char:String):Boolean {
			if (char == null) {
				return false;
			}
			char = trim(char);
			var pattern:RegExp = /^[^\x00-\xff]+$/;
			var result:Object = pattern.exec(char);
			if (result == null) {
				return false;
			}
			return true;
		}
		/**
		 * 是否含有中文字符
		 * @param	char
		 * @return
		 */
		public static function hasChineseChar(char:String):Boolean {
			if (char == null) {
				return false;
			}
			char = trim(char);
			var pattern:RegExp = /[^\x00-\xff]/;
			var result:Object = pattern.exec(char);
			if (result == null) {
				return false;
			}
			return true;
		}
		/**
		 * 支持英文与数字注册字符;
		 * @param	char
		 * @param	len
		 * @return
		 */
		public static function hasAccountChar(char:String,len:uint=15):Boolean {
			if (char == null) {
				return false;
			}
			if (len < 10) {
				len = 15;
			}
			char = trim(char);
			var pattern:RegExp = new RegExp("^[a-zA-Z0-9][a-zA-Z0-9_-]{0,"+len+"}$", "");
			var result:Object = pattern.exec(char);
			if (result == null) {
				return false;
			}
			return true;
		}
		/**
		 * URL地址;
		 * @param	char
		 * @return
		 */
		public static function isURL(char:String):Boolean {
			if (char == null) {
				return false;
			}
			char = trim(char).toLowerCase();
			var pattern:RegExp = /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/;
			var result:Object = pattern.exec(char);
			if (result == null) {
				return false;
			}
			return true;
		}
		/**
		 * 是否为空白字符;
		 * @param	char
		 * @return
		 */
		public static function isWhitespace(char:String):Boolean {
			switch (char) {
				case " " :
					return true;
				case "\t" :
					return true;
				case "\r" :
					return true;
				case "\n" :
					return true;
				case "\f" :
					return true;
				default :
					return false;
			}
		}
		/**
		 * 清除换行符
		 * @param	char
		 * @return
		 */
		public static function clearLine(char:String):String {
			var pattern:RegExp = /\n/; 
			for (var i:uint=0; i<500; i++) {
				if (pattern.test(char)) {
					char=char.replace(pattern,"");
					
				} else {
					return char;
				}
			}
			return char;
		}
		/**
		 * 清除空格符;
		 * @param	char
		 * @return
		 */
		public static function clearSpace(char:String):String {
			var pattern:RegExp = /\s/; 
			for (var i:uint=0; i<500; i++) {
				if (pattern.test(char)) {
					char=char.replace(pattern,"");
					
				} else {
					return char;
				}
			}
			return char;
		}
		/**
		 * 去左右空格;
		 * @param	char
		 * @return
		 */
		public static function trim(char:String):String {
			if (char == null) {
				return null;
			}
			return rtrim(ltrim(char));
		}
		/**
		 * 去左空格; 
		 * @param	char
		 * @return
		 */
		public static function ltrim(char:String):String {
			if (char == null) {
				return null;
			}
			var pattern:RegExp = /^\s*/;
			return char.replace(pattern,"");
		}
		/**
		 * 去右空格;
		 * @param	char
		 * @return
		 */
		public static function rtrim(char:String):String {
			if (char == null) {
				return null;
			}
			var pattern:RegExp = /\s*$/;
			return char.replace(pattern,"");
		}
		/**
		 * 是否为前缀字符串;
		 * @param	char
		 * @param	prefix
		 * @return
		 */
		public static function beginsWith(char:String, prefix:String):Boolean {
			return prefix == char.substring(0,prefix.length);
		}
		/**
		 * 是否为后缀字符串;
		 * @param	char
		 * @param	suffix
		 * @return
		 */
		public static function endsWith(char:String, suffix:String):Boolean {
			return (suffix == char.substring(char.length - suffix.length));
		}
		/**
		 * 去除指定字符串;
		 * @param	char
		 * @param	remove
		 * @return
		 */
		public static function remove(char:String,remove:String):String {
			return replace(char,remove,"");
		}
		/**
		 * 字符串替换;
		 * @param	char
		 * @param	replace
		 * @param	replaceWith
		 * @return
		 */
		public static function replace(char:String, replace:String, replaceWith:String):String {
			return char.split(replace).join(replaceWith);
		}
		/**
		 * utf16转utf8编码;
		 * @param	char
		 * @return
		 */
		public static function utf16to8(char:String):String {
			var out:Array = new Array();
			var len:uint = char.length;
			for (var i:uint=0; i<len; i++) {
				var c:int = char.charCodeAt(i);
				if (c >= 0x0001 && c <= 0x007F) {
					out[i] = char.charAt(i);
				} else if (c > 0x07FF) {
					out[i] = String.fromCharCode(0xE0 | ((c >> 12) & 0x0F),
					 0x80 | ((c >>  6) & 0x3F),
					 0x80 | ((c >>  0) & 0x3F));
				} else {
					out[i] = String.fromCharCode(0xC0 | ((c >>  6) & 0x1F),
					 0x80 | ((c >>  0) & 0x3F));
				}
			}
			return out.join('');
		}
		/**
		 * utf8转utf16编码;
		 * @param	char
		 * @return
		 */
		public static function utf8to16(char:String):String {
			var out:Array = new Array();
			var len:uint = char.length;
			var i:uint = 0;
			var char2:int,char3:int;
			while (i<len) {
				var c:int = char.charCodeAt(i++);
				switch (c >> 4) {
					case 0 :
					case 1 :
					case 2 :
					case 3 :
					case 4 :
					case 5 :
					case 6 :
					case 7 :
						// 0xxxxxxx
						out[out.length] = char.charAt(i-1);
						break;
					case 12 :
					case 13 :
						// 110x xxxx   10xx xxxx
						char2 = char.charCodeAt(i++);
						out[out.length] = String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
						break;
					case 14 :
						// 1110 xxxx  10xx xxxx  10xx xxxx
						char2 = char.charCodeAt(i++);
						char3 = char.charCodeAt(i++);
						out[out.length] = String.fromCharCode(((c & 0x0F) << 12) |
						((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));
						break;
				}
			}
			return out.join('');
		}
		
		/**
		 * 获得省略文本
		 * @author  Johnny Cheng
		 * @param	text 传入字符串
		 * @param	format 传入TextField对应的TextFormat
		 * @param	omitWidth 最大宽度
		 * @param	omit 如果有省略文字，则在其末尾追加的字符串
		 * @return  返回省略到omitWidth宽度以内的字符串
		 */
		public static function getOmitText(text:String, format:TextFormat, omitWidth:Number, omit:String = "..."):String
		{
			tf.defaultTextFormat = format;
			
			// 如果文本宽度小于或等于omitWidth 直接返回text
			tf.text = text;
			if (tf.textWidth <= omitWidth) return text;
			
			var len:int = text.length;
			for (var i:int = 1; i < len; i++) {
				tf.text = text.substr(0, i) + omit;
				if (tf.textWidth > omitWidth) {
					return text.substr(0, i - 1) + omit;
				}
			}
			return text;
		}
		private static const tf:TextField = new TextField();
		
		/**
		 * 替换字符串
		 * @author  Johnny Cheng
		 * @param	source   源字符串
		 * @param	pattern  需要替换的字符串或
		 * @param	callback 对每个匹配到的字符串处理后替换原有字符串
		 * 					 function callback(str:String):String 自动传入被替换的字符串，根据传入字符串修改并返回要替换成的字符串
		 * @return  返回替换后的字符串
		 */
		public static function replaceEx(source:String, pattern:*, callback:Function):String
		{
			var match:Array = source.match(pattern);
			for each(var str:String in match) {
				source = source.replace(str, callback(str));
			}
			return source;
		}
	}
}